 #!/usr/bin/env bash
{ # this ensures the entire script is dowloaded #
flutter_has() {
  type "$1" > /dev/null 2>&1
}

flutter_default_install_dir() {
  [ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.flutter" || printf %s "${XDG_CONFIG_HOME}/flutter"
}

flutter_install_dir() {
  if [ -n "$FLUTTER_DIR" ]; then
    printf %s "${FLUTTER_DIR}"
  else
    flutter_default_install_dir
  fi
}



flutter_profile_is_bash_or_zsh() {
  local TEST_PROFILE
  TEST_PROFILE="${1-}"
  case "${TEST_PROFILE-}" in
    *"/.zshrc" | *"/.bashrc" | *"/.bash_profile" )
      return
    ;;
    *)
      return 1
    ;;
  esac
}

#
# Outputs the location to FLUTTER depending on:
# * The availability of $FLUTTER_SOURCE
# * The method used ("script" or "git" in the script, defaults to "git")
# FLUTTER_SOURCE always takes precedence unless the method is "script-flutter-exec"
#
flutter_source() {
  local FLUTTER_METHOD
  FLUTTER_METHOD="$1"
  local FLUTTER_SOURCE_URL
  FLUTTER_SOURCE_URL="$FLUTTER_SOURCE"
  if [ -z "$FLUTTER_SOURCE_URL" ]; then
    if [ "_$FLUTTER_METHOD" = "_git" ] || [ -z "$FLUTTER_METHOD" ]; then
      FLUTTER_SOURCE_URL="https://gitee.com/mirrors/Flutter.git"
    else
      echo >&2 "Unexpected value \"$FLUTTER_METHOD\" for \$FLUTTER_METHOD"
      return 1
    fi
  fi
  echo "$FLUTTER_SOURCE_URL"
}

#
# Node.js version to install
#
flutter_node_version() {
  echo "$NODE_VERSION"
}

flutter_download() {
  if flutter_has "curl"; then
    curl --compressed -q "$@"
  elif flutter_has "wget"; then
    # Emulate curl with wget
    ARGS=$(echo "$*" | command sed -e 's/--progress-bar /--progress=bar /' \
                            -e 's/-L //' \
                            -e 's/--compressed //' \
                            -e 's/-I /--server-response /' \
                            -e 's/-s /-q /' \
                            -e 's/-o /-O /' \
                            -e 's/-C - /-c /')
    # shellcheck disable=SC2086
    eval wget $ARGS
  fi
}

install_flutter_from_git() {
  local INSTALL_DIR
  INSTALL_DIR="$(flutter_install_dir)"

  if [ -d "$INSTALL_DIR/.git" ]; then
    echo "=> flutter is already installed in $INSTALL_DIR, trying to update using git"
    command printf '
=> '
    command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" fetch origin master --depth=1 2> /dev/null || {
      echo >&2 "Failed to update flutter, run 'git fetch' in $INSTALL_DIR yourself."
      exit 1
    }
  else
    # Cloning to $INSTALL_DIR
    echo "=> Downloading flutter from git to '$INSTALL_DIR'"
    command printf '
=> '
    mkdir -p "${INSTALL_DIR}"
    if [ "$(ls -A "${INSTALL_DIR}")" ]; then
      command git init "${INSTALL_DIR}" || {
        echo >&2 'Failed to initialize flutter repo. Please report this!'
        exit 2
      }
      command git --git-dir="${INSTALL_DIR}/.git" remote add origin "$(flutter_source)" 2> /dev/null \
        || command git --git-dir="${INSTALL_DIR}/.git" remote set-url origin "$(flutter_source)" || {
        echo >&2 'Failed to add remote "origin" (or set the URL). Please report this!'
        exit 2
      }
      command git --git-dir="${INSTALL_DIR}/.git" fetch origin master --depth=1 || {
        echo >&2 'Failed to fetch origin with tags. Please report this!'
        exit 2
      }
    else
      echo "==>flutter_source $(flutter_source)"
      command git -c advice.detachedHead=false clone "$(flutter_source)" -b master  --depth=1 "${INSTALL_DIR}" || {
        echo >&2 'Failed to clone flutter repo. Please report this!'
        exit 2
      }
    fi
  fi
  # command git -c advice.detachedHead=false --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" checkout -f --quiet master
  # if [ -n "$(command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" show-ref refs/heads/master)" ]; then
  #   if command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" branch --quiet 2>/dev/null; then
  #     command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" branch --quiet -D master >/dev/null 2>&1
  #   else
  #     echo >&2 "Your version of git is out of date. Please update it!"
  #     command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" branch -D master >/dev/null 2>&1
  #   fi
  # fi

  echo "=> Compressing and cleaning up git repository"
  if ! command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" reflog expire --expire=now --all; then
    echo >&2 "Your version of git is out of date. Please update it!"
  fi
  if ! command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" gc --auto --aggressive --prune=now ; then
    echo >&2 "Your version of git is out of date. Please update it!"
  fi
  return
}


flutter_try_profile() {
  if [ -z "${1-}" ] || [ ! -f "${1}" ]; then
    return 1
  fi
  echo "${1}"
}

#
# Detect profile file if not specified as environment variable
# (eg: PROFILE=~/.myprofile)
# The echo'ed path is guaranteed to be an existing file
# Otherwise, an empty string is returned
#
flutter_detect_profile() {
  if [ "${PROFILE-}" = '/dev/null' ]; then
    # the user has specifically requested NOT to have flutter touch their profile
    return
  fi

  if [ -n "${PROFILE}" ] && [ -f "${PROFILE}" ]; then
    echo "${PROFILE}"
    return
  fi

  local DETECTED_PROFILE
  DETECTED_PROFILE=''

  if [ -n "${BASH_VERSION-}" ]; then
    if [ -f "$HOME/.bashrc" ]; then
      DETECTED_PROFILE="$HOME/.bashrc"
    elif [ -f "$HOME/.bash_profile" ]; then
      DETECTED_PROFILE="$HOME/.bash_profile"
    fi
  elif [ -n "${ZSH_VERSION-}" ]; then
    DETECTED_PROFILE="$HOME/.zshrc"
  fi

  if [ -z "$DETECTED_PROFILE" ]; then
    for EACH_PROFILE in ".profile" ".bashrc" ".bash_profile" ".zshrc"
    do
      if DETECTED_PROFILE="$(flutter_try_profile "${HOME}/${EACH_PROFILE}")"; then
        break
      fi
    done
  fi

  if [ -n "$DETECTED_PROFILE" ]; then
    echo "$DETECTED_PROFILE"
  fi
}




flutter_do_install() {
  if [ -n "${FLUTTER_DIR-}" ] && ! [ -d "${FLUTTER_DIR}" ]; then
    if [ -e "${FLUTTER_DIR}" ]; then
      echo >&2 "File \"${FLUTTER_DIR}\" has the same name as installation directory."
      exit 1
    fi

    if [ "${FLUTTER_DIR}" = "$(flutter_default_install_dir)" ]; then
      mkdir "${FLUTTER_DIR}"
    else
      echo >&2 "You have \$FLUTTER_DIR set to \"${FLUTTER_DIR}\", but that directory does not exist. Check your profile files and environment."
      exit 1
    fi
  fi
  if [ -z "${METHOD}" ]; then
    # Autodetect install method
    if flutter_has git; then
      install_flutter_from_git
    else
      echo >&2 'You need git to install flutter'
      exit 1
    fi
  elif [ "${METHOD}" = 'git' ]; then
    if ! flutter_has git; then
      echo >&2 "You need git to install flutter"
      exit 1
    fi
    install_flutter_from_git
  else
    echo >&2 "The environment variable \$METHOD is set to \"${METHOD}\", which is not recognized as a valid installation method."
    exit 1
  fi

  echo

  local FLUTTER_PROFILE
  FLUTTER_PROFILE="$(flutter_detect_profile)"
  local PROFILE_INSTALL_DIR
  PROFILE_INSTALL_DIR="$(flutter_install_dir | command sed "s:^$HOME:\$HOME:")"
# flutter and dart 环境变量配置
# export PUB_HOSTED_URL=https://pub.flutter-io.cn
# export FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn
# export FLUTTER_HOME=~/gitee/Flutter
# export DART_HOME=$FLUTTER_HOME/cache/bin/cache/dart-sdk
# export PATH=$FLUTTER_HOME/bin:$DART_HOME/bin:$PATH 
  SOURCE_STR="\n# flutter and dart 环境变量配置\nexport PUB_HOSTED_URL=https://pub.flutter-io.cn\nexport FLUTTER_STORAGE_BASE_URL=https://storage.flutter-io.cn\nexport FLUTTER_HOME=\"${PROFILE_INSTALL_DIR}\"\nexport DART_HOME=\$FLUTTER_HOME/cache/bin/cache/dart-sdk\nexport PATH=\$FLUTTER_HOME/bin:\$DART_HOME/bin:\$PATH
"
  BASH_OR_ZSH=false

  if [ -z "${FLUTTER_PROFILE-}" ] ; then
    local TRIED_PROFILE
    if [ -n "${PROFILE}" ]; then
      TRIED_PROFILE="${FLUTTER_PROFILE} (as defined in \$PROFILE), "
    fi
    echo "=> Profile not found. Tried ${TRIED_PROFILE-}~/.bashrc, ~/.bash_profile, ~/.zshrc, and ~/.profile."
    echo "=> Create one of them and run this script again"
    echo "   OR"
    echo "=> Append the following lines to the correct file yourself:"
    command printf "${SOURCE_STR}"
    echo
  else
    if flutter_profile_is_bash_or_zsh "${FLUTTER_PROFILE-}"; then
      BASH_OR_ZSH=true
    fi
    # TODO:判断条件还有问题,功能基本OK了
    if ${BASH_OR_ZSH} ; then
      echo "=> Appending bash_completion source string to $FLUTTER_PROFILE"
      command printf "$SOURCE_STR" >> "$FLUTTER_PROFILE"
      source $FLUTTER_PROFILE
    fi
  fi


  echo "=> Close and reopen your terminal to start using flutter or run the following to use it now:"
  command printf "${SOURCE_STR}"

  echo "FLUTTER_PROFILE $FLUTTER_PROFILE"

}

[ "_$FLUTTER_ENV" = "_testing" ] || flutter_do_install

} # this ensures the entire script is downloaded #
